package com.tn.service.dwr;

import org.springframework.util.StringUtils;

import com.tn.bo.LoginData;
import com.tn.bo.POHeader;
import com.tn.wservice.validator.IValidationResult;
import com.tn.wservice.validator.ValidationService;
import com.tn.wservice.validator.IValidationResult.Result;
import com.tn.xfer.DwrResponse;
import com.tn.xfer.Registration;

public class ValidationDwr {

	private DwrResponse validate(Object businessObject) {

		DwrResponse validationResponse = new DwrResponse("VALIDATION_RESULT", 0);
		IValidationResult result;
		try {
			result = ValidationService.validate(businessObject);
			if (result.getResult() == Result.FAILURE) {
				validationResponse.setObjRespOrError(result.getErrorMsgs());
				validationResponse.setRespCode(-1);
			} else {
				validationResponse.setObjRespOrError("SUCCESS");
			}
		} catch (Exception e) {
			validationResponse.setObjRespOrError("Exception : "
					+ e.getMessage());
			validationResponse.setRespCode(-1);
		}
		return validationResponse;
	}

	public DwrResponse validateLoginData(LoginData userDetail) {
		DwrResponse result = new DwrResponse("VALIDATION_RESULT", 0);
		try {
			IValidationResult validationResult = ValidationService
					.validate(userDetail);
			if (validationResult.getResult() == Result.FAILURE) {
				result.setObjRespOrError(validationResult.getErrorMsgs());
				result.setRespCode(-1);
			} else {
				// result.setRetMap(validationResult.getUserDetailMap());
				result.setObjRespOrError("SUCCESS");
			}

		} catch (Exception e) {
			result.setObjRespOrError("Exception : " + e.getMessage());
			result.setRespCode(-1);
		}
		return result;
	}

	public DwrResponse validatePOHeader(POHeader poHeader) {
		return validate(poHeader);
	}

	public DwrResponse validateUserExists(String userName) {
		DwrResponse response = new DwrResponse("VALIDATION_RESULT", 0);
		if (userName == null || !StringUtils.hasText(userName)
				|| !ValidationService.isValidEmailAddress(userName)) {
			response.setRespCode(-1);
			response.setErrorMessage("Username must be a valid email address");
			response.setObjRespOrError("Username must be a valid email address");
			return response;
		}
		// If valid userName is supplied, check if it already exists or not
		RegisterDwr registerDwr = new RegisterDwr();
		response = registerDwr.checkUserIdAvailable(userName);
		
		if(response.getRespCode() != 0){
			response.setErrorMessage("Username already exists.");
			response.setObjRespOrError("Username already exists.");
		}
		return response;
	}

	public DwrResponse validateRegistration(Registration reg) {
		String userName = reg.getUserName();
		DwrResponse response = validateUserExists(userName);
		if (response.getRespCode() == 0) {
			return validate(reg);
		} else {
			return response;
		}
	}

}
